//
//  ResumeTplViewController.m
//  eshow
//
//  Created by Hisoka on 15/11/18.
//  Copyright © 2015年 Hisoka. All rights reserved.
//

#import "ResumeTplViewController.h"
#import "ResumeTplTableViewCell.h"
#import "ResumeMakeViewController.h"
#import "ResumePreImageViewController.h"

static NSString * const RESUME_CELL = @"resumeTplCell";
@interface ResumeTplViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tplTV;
@property (nonatomic, strong) NSArray *tplData;
@property (nonatomic, strong) NSString *hasMoreData;
@property (nonatomic, strong) NSString *nextPageNum;
@property (nonatomic, strong) UIScrollView *tplSV;
@property (nonatomic, strong) UIView *pageV;
@property (nonatomic, strong) UIView *fristV;
@property (nonatomic, strong) NSString *preImageName;
@end

@implementation ResumeTplViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customizeBackItem];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    self.navigationItem.title = @"选模板";
    self.view.backgroundColor = GRAY_COLOR;
    self.preImageName = @"resume01Bg";
    [self getResumeList:@"1"];
    
//    [self setStyle];
    
//    [self refresh];
}

- (void) setTplList {
    
    
    
    self.tplSV = [UIScrollView newAutoLayoutView];
    [self.view addSubview:_tplSV];
    
    [_tplSV autoPinToTopLayoutGuideOfViewController:self withInset:3];
    [_tplSV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_tplSV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    [_tplSV autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.view];
    
    _tplSV.backgroundColor = GRAY_COLOR;
    
    for (int i = 0; i < [_tplData count]; i++){
        UIView *bgView = [[UIView alloc] init];
        bgView.frame = CGRectMake(ScreenWidth * i, 0, ScreenWidth, ScreenHeight - 44 - 3 - 20);
        
        
        UIImageView *thumbImg = [UIImageView newAutoLayoutView];
        [bgView addSubview:thumbImg];
        
        [thumbImg autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:bgView];
        [thumbImg autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:bgView];
        [thumbImg autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:bgView];
        [thumbImg autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:bgView];
        
        NSURL *imgUrl = [NSURL URLWithString:[[_tplData objectAtIndex:i] objectForKey:@"thumb"]];
//        NSURL *imgUrl = [NSURL URLWithString:@""];
//        [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBg"]];
//        [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBgwhat.png"]];

        if ([self isiPadModel:[[TMCache sharedCache] objectForKey:@"deviceModel"]] == YES) {
            [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBgiP4"]];
        }else{
            [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBg"]];
        }
        
        UIButton *editBTN = [UIButton newAutoLayoutView];
        [bgView addSubview:editBTN];
        
        [editBTN autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:bgView withOffset:-100];
        [editBTN autoAlignAxis:ALAxisVertical toSameAxisOfView:bgView];
        [editBTN autoSetDimensionsToSize:CGSizeMake(137, 42)];
//        [editBTN setBackgroundColor:ORANGE_COLOR];
//        [editBTN setTitle:@"立即编辑" forState:UIControlStateNormal];
        [editBTN setBackgroundImage:[UIImage imageNamed:@"editResumeICON"] forState:UIControlStateNormal];
        [editBTN addTarget:self action:@selector(pushEditWebV:) forControlEvents:UIControlEventTouchUpInside];
        editBTN.tag = i;
        
        [_tplSV addSubview:bgView];
    }
    
    _tplSV.contentSize = CGSizeMake(ScreenWidth * [_tplData count], ScreenHeight - 44 - 3 - 20);
    _tplSV.contentOffset = CGPointMake(CGRectGetWidth(_tplSV.frame), 0);
    _tplSV.pagingEnabled = YES;
    _tplSV.showsHorizontalScrollIndicator = NO;
    _tplSV.showsVerticalScrollIndicator = NO;
    _tplSV.delegate = self;
    
    [SVProgressHUD dismiss];
    
    if (![[[TMCache sharedCache] objectForKey:@"tplListHasFrist"] isEqualToString:@"1"]) {

    }
    
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger page = floor((_tplSV.contentOffset.x - ScreenWidth / 2) / ScreenWidth) + 1;
    
    _preImageName = [NSString stringWithFormat:@"resume0%ldBg", page+1];
    
    [self setPageNum:page];
    
}

- (void) pushEditWebV:(id)sender {

    UIButton *btn = (UIButton *)sender;
    
    NSDictionary *tmpDic = [_tplData objectAtIndex:btn.tag];
    
    ResumeMakeViewController *resumeMakeVC = [[ResumeMakeViewController alloc] init];
    
    resumeMakeVC.tid = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"id"]];
    resumeMakeVC.title = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"name"]];
    resumeMakeVC.resumeUrl = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"url"]];
    
    [MobClick event:[NSString stringWithFormat:@"Click_ResumeTplList_makeBTN_%@", resumeMakeVC.tid]];
    
    [self.navigationController pushViewController:resumeMakeVC animated:YES];
}

- (void) tplListFristShow {
    self.fristV = [UIView newAutoLayoutView];
    [self.view addSubview:_fristV];
    
    [_fristV autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [_fristV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_fristV autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.view];
    [_fristV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    _fristV.backgroundColor = [UIColor blackColor];
    _fristV.alpha = 0.8;
    
    UIImageView *coverIMG = [UIImageView newAutoLayoutView];
    [_fristV addSubview:coverIMG];
    
    [coverIMG autoAlignAxis:ALAxisVertical toSameAxisOfView:_fristV];
    [coverIMG autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:_fristV withOffset:20];
    [coverIMG autoSetDimensionsToSize:CGSizeMake(ScreenWidth, ScreenWidth * 0.5)];
    coverIMG.image = [UIImage imageNamed:@"resumeFristCover"];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissFristShow)];
    [_fristV addGestureRecognizer:tapRecognizer];
}

- (void) dismissFristShow {
    [[TMCache sharedCache] setObject:@"yes" forKey:@"tplFristShow"];
    [_fristV removeFromSuperview];
}

- (void) setStyle {
    
    self.tplTV = [UITableView newAutoLayoutView];
    [self.view addSubview:_tplTV];
    
    [_tplTV autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [_tplTV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_tplTV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    [_tplTV autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.view];
    
    _tplTV.delegate = self;
    _tplTV.dataSource = self;
    
    [_tplTV registerClass:[ResumeTplTableViewCell class] forCellReuseIdentifier:RESUME_CELL];

    self.hasMoreData = @"0";
    self.nextPageNum = @"2";
    
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tplData.count <= 0) {
        return 0;
    }else{
        return _tplData.count;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 85;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ResumeTplTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RESUME_CELL forIndexPath:indexPath];
    
    NSDictionary *tmpDic = [_tplData objectAtIndex:indexPath.row];
    
    cell.titleLB.text = [tmpDic objectForKey:@"name"];
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *tmpDic = [_tplData objectAtIndex:indexPath.row];
    
    ResumeMakeViewController *resumeMakeVC = [[ResumeMakeViewController alloc] init];
    
    resumeMakeVC.tid = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"id"]];
    resumeMakeVC.title = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"name"]];
    resumeMakeVC.resumeUrl = [NSString stringWithFormat:@"%@", [tmpDic objectForKey:@"url"]];
    
    [self.navigationController pushViewController:resumeMakeVC animated:YES];
}

- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
        [_tplTV.mj_footer beginRefreshing];
        
        if ([_hasMoreData isEqualToString:@"1"]) {
            _tplTV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                if (![_nextPageNum isEqualToString:@"1"]) {
                    [self getResumeList:_nextPageNum];
                }else{
                    [_tplTV.mj_footer endRefreshingWithNoMoreData];
                }
                
            }];
        }else{
            [_tplTV.mj_footer endRefreshingWithNoMoreData];
        }
        
        
    }
}

- (void) getResumeList:(NSString *) pageNum {
    
    [SVProgressHUD show];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[NSString stringWithFormat:@"%@", [[TMCache sharedCache] objectForKey:@"SSID"]] forKey:@"ssid"];
    [parameters setObject:[[TMCache sharedCache] objectForKey:@"deviceModel"] forKey:@"device"];
    [parameters setObject:pageNum forKey:@"p"];
        
    [[HttpManager instance] requestWithMethod:@"Resume/tplList"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          NSDictionary *dataTmp = [result objectForKey:@"data"];
                                          
                                          _tplData = [dataTmp objectForKey:@"list"];
                                          _hasMoreData = [dataTmp objectForKey:@"hasMore"];
                                          
                                          [_tplTV reloadData];
                                          [self setTplList];
                                          [self setPageView];
                                          
                                          NSString *tmpFristShow = [[TMCache sharedCache] objectForKey:@"tplFristShow"];
                                          
                                          if (![tmpFristShow isEqualToString:@"yes"]) {
                                              [self tplListFristShow];
                                          }
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (void) setPageView {
    if ([_tplData count] <= 0) return;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"预览" style:UIBarButtonItemStyleDone target:self action:@selector(preViewResume)];
    self.navigationItem.rightBarButtonItem.tintColor = ORANGE_COLOR;
    
    self.pageV = [UIView newAutoLayoutView];
    [self.view addSubview:_pageV];
    
    [_pageV autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [_pageV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_pageV autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:_tplSV];
    [_pageV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    
    NSInteger pageWidth = ScreenWidth / [_tplData count];

    for (int i = 0; i < [_tplData count]; i++) {
        UILabel *pageLB = [[UILabel alloc] init];
        
        pageLB.frame = CGRectMake(pageWidth * i, 0, ScreenWidth, 3);
        pageLB.tag = i+1;
        
        if (i == 0) {
            pageLB.backgroundColor = ORANGE_COLOR;
        }else{
            pageLB.backgroundColor = WHITE_COLOR;
        }
        
        
        [_pageV addSubview:pageLB];
    }
    
}

- (void) setPageNum:(NSInteger)page {
    
    for (int i = 1; i <= [_tplData count]; i++) {

        UILabel *lb = (UILabel *)[_pageV viewWithTag:i];

        if (i == page+1) {
            lb.backgroundColor = ORANGE_COLOR;
        }else{
            lb.backgroundColor = WHITE_COLOR;
        }
    }
    

}

- (BOOL) isiPadModel:(NSString *)model {
    
    if ([model rangeOfString:@"iPhone4"].location != NSNotFound) return YES;
    
    if ([model rangeOfString:@"iPad"].location != NSNotFound) return YES;
    
    return NO;
}

#pragma mark - 预览模板内容
- (void) preViewResume {
    
    [MobClick event:[NSString stringWithFormat:@"Click_ResumeTplList_preViewBTN_%@", _preImageName]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        ResumePreImageViewController *preImageVC = [[ResumePreImageViewController alloc] init];
        preImageVC.imageName = _preImageName;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:preImageVC];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    });
}

- (void) refresh {
    _tplTV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getResumeList:@"1"];
    }];
    [_tplTV.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
